<?php

namespace App\Models\Base;
use App\Models\BaseModel;

/**
 * 文件存储模型类
 *
 * @package App\Models
 * @author WangBin
 * @date 2021-06-11
 */
class Files extends BaseModel
{
    protected $table = 'base_file';
    protected $primaryKey = 'file_id';

    /**
     * 保存文件
     *
     * @param array $data
     * @return mixed
     */
    public static function saveData(array $data)
    {
        $file = new Files();
        foreach ($data as $field => $value)
        {
            $file->{$field} = $value;
        }
        $file->save();
        return $file;
    }

    /**
     * 获取文件列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(array $filter = [])
    {
        $files = Files::query()->where('is_deleted', 0);
        if(!empty($filter['group_id'])) {
            $files->where('group_id', $filter['group_id']);
        }
        if(!empty($filter['name'])) {
            $files->where('original_name', 'like', '%' . $filter['name'] . '%');
        }
        if(!empty($filter['type'])) {
            $files->where('type', $filter['type']);
        }
        $files->orderByDesc('created_at');
        return $files;
    }

    /**
     * 根据文件ID获取文件信息
     *
     * @param int $fileId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getById(int $fileId)
    {
        return Files::query()->where('file_id', $fileId)->get();
    }

    /**
     * 根据文件ID数组获取文件
     *
     * @param array $fileIds
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getByIds(array $fileIds)
    {
        return Files::query()->whereIn('file_id', $fileIds)->get();
    }
}
